<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="params.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          :data="depts"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          :props="defaultProps"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username?.charAt(row.username.length - 1) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <!-- 聘用形式 1 正式 2 非正式  非1非2 无 -->
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template #default="{row}">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="200px">
            <template #default="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-button size="mini" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total, prev, pager, next"
            :total="total"
            :page-size="params.pagesize"
            :current-page="params.page"
            @current-change="handleChange"
          />
        </el-row>
      </div>
    </div>
    <importExcel :show-excel-dialog.sync="showExcelDialog" @updateSuccess="getEmployeeList" />
    <!-- 弹出层 - 获取可用的角色列表 -->
    <el-dialog title="分配角色" :visible.sync="showRoleDialog">
      <!--roleList 选中的角色列表  -->
      <el-checkbox-group v-model="roleList">
        <el-checkbox
          v-for="item in allRoleList"
          :key="item.id"
          :label="item.id"
        >{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import { getEmployeeList, exportEmployee, getEnableRoleList, getEmployeeDetail, assignRole } from '@/api/employee'
import { transListToTreeData } from '@/utils'
import FileSaver from 'file-saver'
import importExcel from './importExcel.vue'
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      currentUserId: null,
      showRoleDialog: false,
      roleList: [], // 选中的角色列表 - 传递给后端接口
      allRoleList: [], // 所有的角色列表
      showExcelDialog: false,
      depts: [],
      defaultProps: {
        label: 'name'
      },
      params: {
        departmentId: null, // 查询部门的id
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      list: [],
      total: 0
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async btnRoleOK() {
      await assignRole({ roleIds: this.roleList, id: this.currentUserId })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    },
    async btnRole(id) {
      // 1. 获取所有的角色 - 列表
      const result = await getEnableRoleList()
      this.allRoleList = result
      // 存储员工的id
      this.currentUserId = id
      // 2. 获取当前员工所拥有的角色
      const { roleIds } = await getEmployeeDetail(id)
      this.roleList = roleIds
      // 3. 弹出层的显示
      this.showRoleDialog = true
    },
    async exportEmployee() {
      const result = await exportEmployee()
      FileSaver.saveAs(result, '员工表.xlsx')
    },
    async getDepartment() {
      this.depts = transListToTreeData(await getDepartment(), 0)
      // 记录节点 - 围绕右侧表格的数据获取
      this.params.departmentId = this.depts[0].id
      // 设置当前节点的选中状态
      // 数据渲染是异步的 - 一定要保证数据渲染成功在进行实例方法的调用
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.params.departmentId)
      })
      this.getEmployeeList()
    },
    selectNode(node) {
      this.params.departmentId = node.id
      // 重置页码
      this.params.page = 1
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.params)
      this.list = rows
      this.total = total
    },
    handleChange(value) {
      this.params.page = value
      this.getEmployeeList()
    },
    changeValue() {
      // 防抖处理
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.params.page = 1
        this.getEmployeeList()
      }, 300)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
